﻿using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;

namespace 自引用的组织结构树
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            /*
            //插入数据测试
            OrgUnit ouRoot = new OrgUnit() { Name = "xx集团全球总部" };

            OrgUnit ouAsia = new OrgUnit() { Name = "xx集团亚洲总部" };
            OrgUnit ouAmerica = new OrgUnit() { Name = "xx集团美洲总部" };

            OrgUnit ouChina = new OrgUnit() { Name = "xx集团（中国）" };
            OrgUnit ouSingapore = new OrgUnit() { Name = "xx集团（新加坡）" };

            OrgUnit ouUsa = new OrgUnit() { Name = "xx集团（美国）" };
            OrgUnit ouCanada = new OrgUnit() { Name = "xx集团（加拿大）" };

            //把所有子节点加入到父节点中
            ouRoot.Children.Add(ouAsia);
            ouRoot.Children.Add(ouAmerica);

            ouAsia.Children.Add(ouChina);
            ouAsia.Children.Add(ouSingapore);

            ouAmerica.Children.Add(ouUsa);
            ouAmerica.Children.Add(ouCanada);

            using (var db = new MyContext())
            {
                db.OrgUnits.Add(ouRoot);
                await db.SaveChangesAsync();
            }
            */


            //打印子节点
            using (var db = new MyContext())
            {
                OrgUnit orgRoot = db.OrgUnits.Single(x => x.Parent == null);//根节点
                Console.WriteLine(orgRoot.Name);
                PrintChildren(db, 1, orgRoot);
            }
        }

        //递归打印指定节点下的所有子节点
        static void PrintChildren(MyContext db, int identLevel, OrgUnit orgUnit)
        {
            var children = db.OrgUnits.Where(x => x.Parent == orgUnit);

            foreach (var child in children)
            {
                Console.WriteLine(new string('\t', identLevel) + child.Name);
                PrintChildren(db, identLevel + 1, child);   //递归：打印以我为父节点的所有子节点
            }
        }
    }
}
